#include "LinkedList.h"
#include <fstream>
#include <sstream>

using namespace std;

LinkedList::LinkedList()
{
	mpHead = NULL;
}

LinkedList::~LinkedList()
{
	removeAllWords();
}

void LinkedList::addWord( const string& theWord )
{
	//create a ListNode
	ListNode* pNode = new ListNode( theWord );

	//add it at the tail

	if( mpHead != NULL )//head exists
	{
		ListNode* pCurrent = mpHead;

		while( pCurrent->pNextNode != NULL )
		{
			pCurrent = pCurrent->pNextNode;
		}
		//pCurrent now points to the tail
		pCurrent->pNextNode = pNode;
	}
	else//head doesn't exist
	{
		mpHead = pNode;
	}
}

void LinkedList::removeWord( const string& theWord )
{
	if( mpHead != NULL )//something in the list
	{
		ListNode* pCurrent = mpHead;
		ListNode* pPrevious = NULL;

		while( pCurrent->pNextNode != NULL )
		{
			if( pCurrent->word == theWord )
			{
				//found the word - remove it

				if( pPrevious == NULL )//word was found at the head
				{
					mpHead = pCurrent->pNextNode;
					delete pCurrent;
				}
				else//word found somewhere else
				{
					pPrevious->pNextNode = pCurrent->pNextNode;
					delete pCurrent;
				}
				break;
			}
			else
			{
				pCurrent = pCurrent->pNextNode;
			}
		}
	}
}

void LinkedList::removeAllWords()
{
	ListNode* pCurrent = mpHead;
	while( pCurrent != NULL )
	{
		ListNode* pTemp = pCurrent;
		pCurrent = pCurrent->pNextNode;
		delete pTemp;
	}
	mpHead = NULL;
}

string LinkedList::getReport() const
{
	stringstream theStream;

	ListNode* pCurrent = mpHead;

	while( pCurrent != NULL )
	{
		theStream << pCurrent->word << " ";
		pCurrent = pCurrent->pNextNode;
	}
	return theStream.str();
}

/*
BackwardLinkedList::BackwardLinkedList()
	:LinkedList()
{
}

BackwardLinkedList::~BackwardLinkedList()
{
	LinkedList::~LinkedList();
}

void BackwardLinkedList::addWord( const string& theWord )
{
	LinkedList::ListNode* pNode = new ListNode( theWord, mpHead );
	mpHead = pNode;
}*/